#include "config.h"
#include "Proxy.h"

using namespace std;

void commands()
{
	cout << "Available Commands:" <<endl;
	cout << "x: exit" << endl;
	cout << endl;
}

void usage( const char* program_name )
{
	cout << "Usage: " << program_name << " [options]" << endl;
	cout << "Options" << endl;
	cout << "  -p port" << endl;
	cout << "  -s ssl_port" << endl;
	cout << "More Options" << endl;
	cout << "  -g level (1-10)" << endl;
	cout << "  -i ca_certificate_path" << endl;
	cout << "  -j server_certificate_path" << endl;
	cout << "  -k server_privatekey_path" << endl;
}

void StartConsole( Proxy* proxy )
{
	char console_cmd = ' ';
	string tmp = "";
	commands();
	while( console_cmd != 'x' )
	{
		cout << "\nPlease enter command" << endl;
		cin >> tmp;
		console_cmd = tmp[0];

		switch( console_cmd )
		{
			case 'x':
				break;
			default:
				commands();
		}
	}

	cout << "bye" << endl;
	proxy->Stop();
}

int main( int argc, char* argv[] )
{
	// Default
	unsigned short listen_port = 3128;
	unsigned short ssl_listen_port = 3129;
	const char* server_port_string = "";
	const char* ca_certificate_path = "ca_certificate.pem";
	const char* srv_certificate_path = "srv_certificate.pem";
	const char* srv_privatekey_path = "srv_privatekey.pem";
	int level = 2;   // DEBUG_LEVEL_DEBUG

	// Parse arguments
	int c;
	while ((c = getopt(argc, argv, "p:s:g:i:j:k:")) != -1) {
		switch (c) {
			case 'p':
				listen_port = atoi(optarg);
				break;
			case 's':
				ssl_listen_port = atoi(optarg);
				break;
			case 'g':
				level = atoi(optarg);
				break;
			case 'i':
				ca_certificate_path = optarg;
				break;
			case 'j':
				srv_certificate_path = optarg;
				break;
			case 'k':
				srv_privatekey_path = optarg;
				if (level <= 0 || level > 10) level = 2;
				break;
			default:
				usage( argv[1] );
				exit(1);
				break;
		}
	}
	
	Proxy proxy;
	proxy.SetNormalServer( listen_port );
	proxy.SetSSLServer( ssl_listen_port, ca_certificate_path, srv_certificate_path, srv_privatekey_path );
	proxy.Start();
	StartConsole( &proxy );
	
	return 0;
}
